/**
 * 
 */
package Bai4;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.JPanel;
import javax.swing.Timer;

/**
 * @author Nguyen Tuan Luc T127536
 * 
 */
public class cHW05_TrafficPanel04_T127536 extends JPanel {

	int nNumberImg = 1;
	int iCurrentImg = 0;
	// khai bao duong dan cua img
	String[] sImgFileName = { ".\\pics05\\SmallRedCar\\Car-04.gif"};
	String[] sImgFileName2 = { ".\\pics05\\SmallRedCar\\Car-00.gif"};
	// khai bao bien de doc image vao bo nho
	BufferedImage[] imgs = new BufferedImage[nNumberImg];
	BufferedImage[] imgs2 = new BufferedImage[nNumberImg];
	Timer t;
	int x = 380, y = 700, dx = 10, dy = 10;
	
	int direction = 0; // 0: LEFT to RIGHT
	int direction2 = 1; // 0: LEFT to RIGHT

	public cHW05_TrafficPanel04_T127536() {

		try {
			// doc hinh anh luu vao bo nho (memory)
			for (int i = 0; i < nNumberImg; i++) {
				imgs[i] = ImageIO.read(new File(sImgFileName[i]));
				imgs2[i] = ImageIO.read(new File(sImgFileName2[i]));
			}
		} catch (IOException e) {
			// error off reading the file
			System.err.println("loading error");
		}
		t = new Timer(25, new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent arg0) {
				// TODO Auto-generated method stub
				y = y - dy;
			}
		});
	}

	public void paint(Graphics g) {
		super.paint(g);
		g.setColor(Color.BLACK);
		g.fillRect(0, 0, 70, 700);
		g.fillRect(610, 0, 70, 700);
		for ( int i = 0 ; i <700; i+=80){
			g.setColor(Color.WHITE);
			g.fillRect(350, 0, 5, 700);
		}
	

		// display image

		if (direction == 1) {
			g.drawImage(imgs[iCurrentImg], x, y, this);
		} else {
			g.drawImage(imgs[iCurrentImg], x, y, this);
		}
		if( x < 50){
			x = 50;
		}
		if ( y == -100){
			y = 700;
		}
		if ( y > 750){
			y = -80;
		}
		if(x>540){
			x=540;
		}
		repaint();
		// g.drawImage(imgs[1], 10, 50, this);
	}

	public void MoveUp() {
		if (direction == 1) {
			direction = 0;
			dy = -dy;
		}
		iCurrentImg++;
		if (iCurrentImg == nNumberImg) {
			iCurrentImg = 0;
		}
		y = y + dy;
	}

	public void moveDown() {
		if (direction == 0) {
			direction = 1;
			dy = -dy;
		}
		iCurrentImg++;
		if (iCurrentImg == nNumberImg) {
			iCurrentImg = 0;
		}
		y = y + dy;

	}
	
	public void MoveLeft() {
		if (direction2 == 1) {
			direction2 = 0;
			dx = - dx;
			
		}
		iCurrentImg++;
		if (iCurrentImg == nNumberImg) {
			iCurrentImg = 0;
		}
		x = x + dx;
	}

	public void moveRight() {
		if (direction2 == 0) {
			direction2 = 1;
			dx = -dx;
		}
		iCurrentImg++;
		if (iCurrentImg == nNumberImg) {
			iCurrentImg = 0;
		}
		x = x + dx;

	}
	public void start() {
		t.start();
	}

	public void stop() {
		t.stop();
	}
}
